import { createRouter, createWebHashHistory } from 'vue-router';
import Home from '@/components/Home.vue';
import storage from './../utils/storage';
import API from './../api';
import utils from './../utils/utils';
import { defineAsyncComponent } from 'vue';
// console.log(process.env)
// console.log($env)
// const _import = (path) => defineAsyncComponent(() => import(/* @vite-ignore */ `../views${path}.vue`));
// const _import = (path) => () => import(/* @vite-ignore */ `../views${path}.vue`);
const modules = import.meta.glob('../views/**/*.vue');
const routes = [
  {
    name: 'home',
    path: '/',
    meta: {
      title: '首页'
    },
    component: Home,
    redirect: '/welcome',
    children: [
      {
        name: 'welcome',
        path: '/welcome',
        meta: {
          title: '欢迎体验Vue3全栈课程'
        },
        component: () => import('@/views/Welcome.vue')
      }
    ]
  },
  {
    name: 'login',
    path: '/login',
    meta: {
      title: '登录'
    },
    component: () => import('@/views/Login.vue')
  },
  {
    name: '404',
    path: '/404',
    meta: {
      title: '页面不存在'
    },
    component: () => import('@/views/404.vue')
  },
  // vue3 新做法
  {
    path: '/:catchAll(.*)', // 不识别的path自动匹配404
    redirect: '/404'
  }
];
const router = createRouter({
  history: createWebHashHistory(),
  routes
});

async function loadAsyncRoutes() {
  const userInfo = storage.getItem('userInfo') || {};
  if (userInfo.token) {
    try {
      const { menuList } = await API.getPermissionList();
      const routes = utils.generateRoute(menuList);
      routes.map((route) => {
        // console.log(route);
        // let url = `../views/${route.component}`;
        // let url = `./../views/${route.component}.vue`;
        // route.component = () => import(/* @vite-ignore */ `${url}`);
        // let url = route.component;
        // route.component = _import(/* @vite-ignore */ url);
        const url = `../views${route.component}.vue`;
        // console.log(modules, url, modules[url]);
        route.component = modules[url];
        if (route.component) router.addRoute('home', route);
      });
      //   console.log(router);
      // 导航守卫
      router.beforeEach((to, from, next) => {
        console.log('to=>', to);
        if (router.hasRoute(to.name)) {
          document.title = to.meta.title;
          next();
        } else {
          next('/404');
        }
      });
    } catch (error) {
      console.log(error);
    }
  }
}
console.log(123);
// await loadAsyncRoutes();
await loadAsyncRoutes();
// (async () => await loadAsyncRoutes())();
// load();
// 判断当前地址是否可以访问
/*
function checkPermission(path) {
    let hasPermission = router.getRoutes().filter(route => route.path == path).length;
    if (hasPermission) {
        return true;
    } else {
        return false;
    }
}
*/

export default router;
